package com.zhilianbao.leyaogo.ui.fragment.me.myorder;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.animationcheckbox.AnimationCheckBox;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.NumberUtlis;
import com.bql.utils.ThreadPool;
import com.bql.utils.ToastUtils;
import com.google.gson.Gson;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.alipay.AliPayUtil;
import com.zhilianbao.leyaogo.alipay.IPayCallBack;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.constants.PayConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.PayApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.me.MyOrderResponse;
import com.zhilianbao.leyaogo.model.response.me.PayMentBackResponse;
import com.zhilianbao.leyaogo.model.response.shoppingcart.MyBalance;
import com.zhilianbao.leyaogo.model.response.shoppingcart.WXPay;
import com.zhilianbao.leyaogo.ui.activity.me.ServiceAndHelpActivity;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.BalanceActivity;
import com.zhilianbao.leyaogo.ui.activity.me.setting.SetPwdActivity;
import com.zhilianbao.leyaogo.ui.adapter.me.OrderDetailListAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.PayByBalanceFragment;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.PaySuccessFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.WXPayUtils;
import com.zhilianbao.leyaogo.utils.XTipsDialog;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.dialog.ConfirmPayDialog;
import com.zhilianbao.leyaogo.view.dialog.PayTypeSelectDialog;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;
import com.zhilianbao.leyaogo.view.widgets.SelectPayMethodView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/10/25.
 * 订单详情
 */
public class OrderDetailFragment extends BaseOkHttpFragment {

    @BindView(R.id.order_detail_listview)
    ListView mOrderDetailListView;
    @BindView(R.id.detail_order_num)
    TextView mDetailOrderNum;
    @BindView(R.id.detail_order_state)
    TextView mDetailOrderState;
    @BindView(R.id.tv_ad_name)
    TextView mTvAdName;
    @BindView(R.id.tv_ad_phone_num)
    TextView mTvAdPhoneNum;
    @BindView(R.id.tv_str_address)
    TextView mStrAddress;
    @BindView(R.id.tv_pay_goods_total)
    MoneyTextView mTvPayGoodsTotal;
    @BindView(R.id.tv_pay_logistic)
    MoneyTextView mTvPayLogistic;
    @BindView(R.id.tv_coupon)
    MoneyTextView mTvCoupon;
    @BindView(R.id.tv_credits)
    MoneyTextView mTvCredits;
    @BindView(R.id.tv_balance)
    MoneyTextView mTvBalance;
    @BindView(R.id.tv_pay_total)
    MoneyTextView mTvPayTotal;
    @BindView(R.id.tv_goods_count)
    TextView mTvGoodsCount;
    @BindView(R.id.view_pay_method)
    SelectPayMethodView mViewPayMethod;
    @BindView(R.id.tv_cancel_order)
    TextView tvCancelOrder;
    @BindView(R.id.tv_pay_now)
    TextView tvPayNow;
    @BindView(R.id.tv_coupon_minus)
    TextView tvCouponMinus;
    @BindView(R.id.tv_credits_minus)
    TextView tvCreditsMinus;
    @BindView(R.id.tv_balance_minus)
    TextView tvBalanceMinus;
    private static long mUserId;
    private static long mOrderId;
    private static int position;
    @BindView(R.id.tv_goods_send_time)
    TextView tvGoodsSendTime;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_pay_type_all)
    TextView tvPayTypeAll;
    @BindView(R.id.tv_invoice_start)
    TextView tvInvoiceStart;
    @BindView(R.id.ll_pay_type)
    LinearLayout llPayType;
    @BindView(R.id.ll_invoice)
    LinearLayout llInvoice;
    @BindView(R.id.rl_send_time)
    RelativeLayout rlSendTime;
    private AlertDialog mDialog;
    private TextView mContent;
    private TextView mSure;
    private TextView mTvCancel;

    //支付相关
    private ConfirmPayDialog confirmPayDialog;
    private PayTypeSelectDialog payTypeSelectDialog;
    private int mPayType;//底部支付方式
    //    private IWXAPI wxApi;

    private MyOrderResponse mAddedOrderInfo;//生成的订单信息

    private MyBalance mMyBalance;//账户余额信息

    private int mDialogPayType = PayConfig.WX_PAY;//对话框支付方式

    private double needToPayPrice;//需付款

    private boolean checkBoxState = true;//余额抵扣选中状态
    private CommonDialog mCommonDialog;


    public static OrderDetailFragment getInstance(long userId, long orderId, int position) {
        OrderDetailFragment.mUserId = userId;
        OrderDetailFragment.mOrderId = orderId;
        OrderDetailFragment.position = position;
        OrderDetailFragment fragment = new OrderDetailFragment();
        return fragment;
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.order_detail_page));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initData();
    }


    private void initData() {
        mPayType = Utils.getLastPayType();
        //        wxApi = WXAPIFactory.createWXAPI(mActivity, PayConfig.WX_APP_ID, true);
        //        wxApi.registerApp(PayConfig.WX_APP_ID);
        AccountApi.getOrderDetail(mActivity, mOrderId, mUserId, new LoadingViewCallback<MyOrderResponse>(mActivity, getView(), false) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                initData();
            }

            @Override
            public void onResultSuccess(MyOrderResponse myOrderResponse, @Nullable Response response, LoadingViewCallback callback) {
                mAddedOrderInfo = myOrderResponse;
                initView(myOrderResponse);
                initListView(myOrderResponse.getOrderItem());
            }

        });
    }

    private void initView(MyOrderResponse myOrderResponse) {
        mDetailOrderNum.setText("订单编号:" + myOrderResponse.getOrderNo());
        setOrderState(myOrderResponse);
        mTvAdName.setText(myOrderResponse.getAdName());
        mTvAdPhoneNum.setText(myOrderResponse.getAdPhone());
        mStrAddress.setText(myOrderResponse.getStrAddress());
        mTvPayGoodsTotal.setAmount(myOrderResponse.getTotalPrice());
        mTvPayLogistic.setAmount(myOrderResponse.getPostPrice());
        mTvCoupon.setAmount(myOrderResponse.getCouponsPrice());
        //设置送货时间
        if (myOrderResponse.getStrVal1() == null || myOrderResponse.getStrVal1().equals("")) {
            rlSendTime.setVisibility(View.GONE);
        } else {
            rlSendTime.setVisibility(View.VISIBLE);
            tvGoodsSendTime.setText(myOrderResponse.getStrVal1());
        }
        if (myOrderResponse.getHasInvoice() == 0) {//不开发票
            tvInvoiceStart.setText("不开发票");
        } else if (myOrderResponse.getHasInvoice() == 1) {//开发票
            tvInvoiceStart.setText(myOrderResponse.getInvoiceTitle());
        }
        //设置支付方式
        if (myOrderResponse.getPayType() == 0) {//电商支付
            String paymentBack = myOrderResponse.getPaymentBack();
            if (paymentBack == null) {
                llPayType.setVisibility(View.GONE);
            } else {
                llPayType.setVisibility(View.VISIBLE);
                PayMentBackResponse payMentBackResponse = new Gson().fromJson(paymentBack, PayMentBackResponse.class);
                String account = payMentBackResponse.getPayItems().getACCOUNT();
                String alipay = payMentBackResponse.getPayItems().getALIPAY();
                String weixin = payMentBackResponse.getPayItems().getWEIXIN();
                if (!CheckUtils.isEmpty(account) && !CheckUtils.isEmpty(alipay)) {//余额,支付宝混合支付
                    tvPayType.setText("余额支付");
                    tvPayTypeAll.setVisibility(View.VISIBLE);
                    tvPayTypeAll.setText("+ 支付宝支付");
                } else if (!CheckUtils.isEmpty(account) && !CheckUtils.isEmpty(weixin)) {//余额微信混合支付
                    tvPayType.setText("余额支付");
                    tvPayTypeAll.setVisibility(View.VISIBLE);
                    tvPayTypeAll.setText("+ 微信支付");
                } else if (!CheckUtils.isEmpty(account)) {//余额支付
                    tvPayTypeAll.setVisibility(View.GONE);
                    tvPayType.setText("余额支付");
                } else if (!CheckUtils.isEmpty(alipay)) {//支付宝支付
                    tvPayTypeAll.setVisibility(View.GONE);
                    tvPayType.setText("支付宝支付");
                } else if (!CheckUtils.isEmpty(weixin)) {//微信支付
                    tvPayTypeAll.setVisibility(View.GONE);
                    tvPayType.setText("微信支付");
                }else {
                    llPayType.setVisibility(View.GONE);
                }
            }
        } else if (myOrderResponse.getPayType() == 1) {//货到付款
            tvPayType.setText("货到付款");
        }

        //设置优惠抵扣前面的减号
        if (myOrderResponse.getCouponsPrice() == 0) {
            tvCouponMinus.setVisibility(View.GONE);
        }
        mTvCredits.setAmount(myOrderResponse.getRechargeCardPrice());
        if (myOrderResponse.getRechargeCardPrice() == 0) {
            tvCreditsMinus.setVisibility(View.GONE);
        }
        mTvBalance.setAmount(myOrderResponse.getActivityPrice());
        if (myOrderResponse.getActivityPrice() == 0) {
            tvBalanceMinus.setVisibility(View.GONE);
        }
        mTvGoodsCount.setText("共" + (CheckUtils.isEmpty(myOrderResponse.getOrderItem()) ? "0" : myOrderResponse.getOrderItem().size()) + "件商品");
        double payTotalPrice = NumberUtlis.sub(NumberUtlis.add(myOrderResponse.getTotalPrice(), myOrderResponse.getPostPrice()), NumberUtlis.add(NumberUtlis.add(myOrderResponse.getCouponsPrice(), myOrderResponse.getRechargeCardPrice()), myOrderResponse.getActivityPrice()));
        mTvPayTotal.setAmount(payTotalPrice);
        mViewPayMethod.setPayMethod(mPayType);
    }

    //设置订单状态
    private void setOrderState(MyOrderResponse myOrderResponse) {
        switch (myOrderResponse.getOrderCode()) {
            case 1://待确认
            case 2://已确认
            case 3://未支付(暂时都统一为待支付)
                mDetailOrderState.setText("待付款");
                setButtonVisible(View.VISIBLE, View.VISIBLE);
                setButtonText("取消订单", "立即支付");
                mViewPayMethod.setVisibility(View.VISIBLE);
                llPayType.setVisibility(View.GONE);
                break;
            case 4://已支付
                mDetailOrderState.setText("待发货");
                setButtonVisible(View.VISIBLE, View.GONE);
                setButtonText("申请售后", null);
                mViewPayMethod.setVisibility(View.GONE);
                llPayType.setVisibility(View.VISIBLE);
                break;
            case 5://已发货
                mDetailOrderState.setText("待收货");
                setButtonVisible(View.VISIBLE, View.GONE);
                setButtonText("确认收货", null);
                mViewPayMethod.setVisibility(View.GONE);
                llPayType.setVisibility(View.VISIBLE);
                break;
            case 6://已完成
                mDetailOrderState.setText("已完成");
                setButtonVisible(View.VISIBLE, View.GONE);
                setButtonText("申请售后", null);
                mViewPayMethod.setVisibility(View.GONE);
                llPayType.setVisibility(View.VISIBLE);
                break;
            case 99://已取消
                mDetailOrderState.setText("已取消");
                setButtonVisible(View.VISIBLE, View.GONE);
                mViewPayMethod.setVisibility(View.GONE);
                setButtonText("删除订单", null);
                llPayType.setVisibility(View.GONE);
        }
    }

    private void setButtonVisible(int a, int b) {
        tvCancelOrder.setVisibility(a);
        tvPayNow.setVisibility(b);
    }

    //设置2个按钮的文字
    private void setButtonText(String s1, String s2) {
        tvCancelOrder.setText(s1);
        tvPayNow.setText(s2);
    }

    private void initListView(List<MyOrderResponse.OrderItemBean> orderItem) {
        mOrderDetailListView.setAdapter(new OrderDetailListAdapter(mActivity, orderItem));
        mOrderDetailListView.setDividerHeight(1);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_order_detail;
    }

    @OnClick({R.id.tv_cancel_order, R.id.tv_pay_now})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel_order:
                String cancel = tvCancelOrder.getText().toString().trim();
                if ("取消订单".equals(cancel)) {
                    //                    cancelOrderDialog();
                    showCancelDialog();
                } else if ("删除订单".equals(cancel)) {
                    //                    deleteDialog();
                    showDelDialog();
                } else if ("确认收货".equals(cancel)) {
                    //                    sureReceive();
                    showSureReceiveDialog();
                } else if ("申请售后".equals(cancel)) {
                    Utils.startActivity(mActivity, ServiceAndHelpActivity.class);
                    //                    mActivity.finish();
                }
                break;
            case R.id.tv_pay_now:
                if (mAddedOrderInfo.getPaymentPrice() == 0) {
                    start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                } else {
                    if (mViewPayMethod.getPayMethod() != -1) {
                        //如果选择微信支付 先判断是否支付微信客户端支付 （是否支持支付版本 和 是否安装客户端）
                        if (mViewPayMethod.getPayMethod() != PayConfig.WX_PAY || (mViewPayMethod.getPayMethod() == PayConfig.WX_PAY && WXPayUtils.checkIsSupportWXPay(mActivity))) {

                            if (mViewPayMethod.getPayMethod() == PayConfig.WX_PAY) {
                                invokeWXPay(mAddedOrderInfo, mAddedOrderInfo.getPaymentPrice(), null);
                            } else if (mViewPayMethod.getPayMethod() == PayConfig.ALI_PAY) {
                                invokeAliPay(mAddedOrderInfo, mAddedOrderInfo.getPaymentPrice(), null);
                            } else if (mViewPayMethod.getPayMethod() == PayConfig.YUE_PAY) {
                                useMyBalancePay(mAddedOrderInfo);
                            }
                        }
                    } else {
                        XToastUtils.showShortToast(getString(R.string.please_select_pay_type));
                    }
                }
                break;
        }
    }

 /*   //弹出确认收货dialog
    private void sureReceive() {
        View view = View.inflate(mActivity, R.layout.corner_dialog_sure_receive, null);
        initDialog(view, 236, 130);
        mContent.setText("确认收货后,资金将转入卖家,确认收货吗?");
        mSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 2;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        mAddedOrderInfo.setOrderCode(6);
                        mDetailOrderState.setText("已完成");
                        tvCancelOrder.setText("申请售后");
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_SURE_RECEIVE));
                    }
                });
                mDialog.dismiss();
            }
        });
    }


    //弹出删除dialog
    private void deleteDialog() {
        View view = View.inflate(mActivity, R.layout.corner_dialog, null);
        initDialog(view, 236, 108);
        mContent.setText("删除后无法恢复,确定要删除吗?");
        mSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 0;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_DELETE,position));
                        mActivity.finish();
                    }
                });
                mDialog.dismiss();
            }
        });
    }

    //弹出取消订单dialog
    private void cancelOrderDialog() {
        View view = View.inflate(mActivity, R.layout.corner_dialog, null);
        initDialog(view, 236, 108);
        mContent.setText("确定取消订单吗?");
        mSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //订单由待支付状态变为已取消状态
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 1;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        ToastUtils.showShort(mActivity, "取消订单成功");
                        mAddedOrderInfo.setOrderCode(99);
                        mDetailOrderState.setText("已取消");
                        tvCancelOrder.setText("删除订单");
                        tvPayNow.setVisibility(View.GONE);
                        mViewPayMethod.setVisibility(View.GONE);
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_CANCEL));
                    }
                });
                mDialog.dismiss();
            }
        });
    }

    //初始化dialog
    private void initDialog(View view, float width, float height) {
        mDialog = Utils.showCornerDialog(mActivity, view, width, height);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setCancelable(false);
        mContent = (TextView) mDialog.findViewById(R.id.tv_dialog_content);
        mSure = (TextView) mDialog.findViewById(R.id.tv_dialog_sure);
        mTvCancel = (TextView) mDialog.findViewById(R.id.tv_dialog_cancel);
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }*/

    /**
     * 删除提示框
     */
    private void showDelDialog() {
        if (mCommonDialog == null) {
            mCommonDialog = CommonDialog.createTwoButton(getString(R.string.confirm), getString(R.string.cancel), "删除后无法恢复,确定要删除吗?");
        }
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 0;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_DELETE, position));
                        mActivity.finish();
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(getFragmentManager(), "delete");
    }

    /**
     * 取消提示框
     */
    private void showCancelDialog() {
        if (mCommonDialog == null) {
            mCommonDialog = CommonDialog.createTwoButton(getString(R.string.confirm), getString(R.string.cancel), "确定取消订单吗?");
        }
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                //订单由待支付状态变为已取消状态
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 1;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        ToastUtils.showShort(mActivity, "取消订单成功");
                        mAddedOrderInfo.setOrderCode(99);
                        mDetailOrderState.setText("已取消");
                        tvCancelOrder.setText("删除订单");
                        tvPayNow.setVisibility(View.GONE);
                        mViewPayMethod.setVisibility(View.GONE);
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_CANCEL));
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(getFragmentManager(), "cancel");
    }

    /**
     * 确认收货提示框
     */
    private void showSureReceiveDialog() {
        if (mCommonDialog == null) {
            mCommonDialog = CommonDialog.createTwoButton(getString(R.string.confirm), getString(R.string.cancel), "确认收货后,资金将转入卖家,确认收货吗?");
        }
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                long orderId = mAddedOrderInfo.getOrderId();
                long userId = mAddedOrderInfo.getUserId();
                int type = 2;
                AccountApi.setOrder(mActivity, orderId, userId, type, new DialogCallback<Object>(mActivity) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        XToastUtils.showShortToast("收货完成");
                        mAddedOrderInfo.setOrderCode(6);
                        mDetailOrderState.setText("已完成");
                        tvCancelOrder.setText("申请售后");
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_DETAIL_SURE_RECEIVE));
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(getFragmentManager(), "sure_receive");
    }


    /**
     * 调用微信支付
     *
     * @param orderInfo        订单消息
     * @param paymentPrice     需付款
     * @param availableBalance 可用余额 混合支付用到
     */
    private void invokeWXPay(MyOrderResponse orderInfo, double paymentPrice, Double availableBalance) {
        PayApi.wxpay(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 0, paymentPrice, availableBalance, orderInfo.getOrderId(), orderInfo.getOrderNo(), new DialogCallback<WXPay>(mActivity, getString(R.string.get_wxpay_info)) {
            @Override
            public void onSuccess(WXPay pay, Call call, Response response) {
                WXPayUtils.payByWX(pay);
            }
        });
    }

    /**
     * 调用支付宝支付
     *
     * @param orderInfo 订单消息
     */
    private void invokeAliPay(MyOrderResponse orderInfo, double paymentPrice, Double availableBalance) {
        PayApi.alipay(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 0, paymentPrice, availableBalance, orderInfo.getOrderId(), orderInfo.getOrderNo(), new DialogCallback<String>(mActivity, getString(R.string.get_alipay_info)) {
            @Override
            public void onSuccess(String pay, Call call, Response response) {
                payByALi(pay);
            }
        });
    }

    /**
     * 调用余额支付
     *
     * @param orderInfo 订单消息
     */
    private void useMyBalancePay(MyOrderResponse orderInfo) {
        PayApi.getMyBalance(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), new DialogCallback<MyBalance>(mActivity, getString(R.string.get_available_balance)) {
            @Override
            public void onSuccess(MyBalance balance, Call call, Response response) {
                mDialogPayType = PayConfig.WX_PAY;
                mMyBalance = balance;
                checkBoxState = true;
                needToPayPrice = NumberUtlis.sub(orderInfo.getPaymentPrice(), balance.getAvailableBalance());
                //余额足够  全余额支付 首先要判断是否设置了支付密码
                if (balance.getAvailableBalance() >= orderInfo.getPaymentPrice()) {
                    ThreadPool.postOnUiDelayed(() ->
                                    PayApi.hasSetPayPwd(mActivity, new DialogCallback<String>(mActivity, getString(R.string.verify_pay_environment)) {
                                        @Override
                                        public void onSuccess(String o, Call call, Response response) {
                                            if (CheckUtils.equalsString(o, HttpConfig.MSG_ERROR_CODE_10046 + "")) {
                                                XTipsDialog.showFail(mActivity, getString(R.string.set_pay_pwd_first), () -> Utils.startActivity(mActivity, SetPwdActivity.class));
                                            } else {
                                                start(PayByBalanceFragment.getInstance(mAddedOrderInfo));
                                            }
                                        }
                                    })
                            , 300);
                }
                //余额为0  提示充值对话框
                else if (balance.getAvailableBalance() == 0) {
                    showGoToChargeDialog();
                }
                //余额不足结合第三方支付平台支付
                else {
                    needToPayPrice = NumberUtlis.sub(orderInfo.getPaymentPrice(), balance.getAvailableBalance());
                    XTipsDialog.showFail(mActivity, getString(R.string.balance_not_enough), () -> showPayDetailDialog(mDialogPayType, orderInfo.getPaymentPrice(), balance.getAvailableBalance(), needToPayPrice, checkBoxState));
                }
            }
        });
        //        start(PayByBalanceFragment.getInstance());
    }

    /**
     * 弹出付款详情 对话框
     */
    private void showPayDetailDialog(int payType, double total, double balance, double needToPay, boolean state) {
        confirmPayDialog = new ConfirmPayDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.PAY_TYPE, payType);
        bundle.putDouble(IntentConfig.PAY_TOTAL_PRICE, total);
        bundle.putDouble(IntentConfig.PAY_AVAILABLE_BALANCE, balance);
        bundle.putDouble(IntentConfig.PAY_NEED_TO_PAY_PRICE, needToPay);
        bundle.putBoolean(IntentConfig.BALANCE_CHECKBOX_STATE, state);
        confirmPayDialog.setArguments(bundle);
        confirmPayDialog.setPayTypeSelectListener(new ConfirmPayDialog.OnMultiClickListener() {

            @Override
            public void onCheckChanged(AnimationCheckBox checkBox, boolean isChecked, double needToPay) {
                checkBoxState = isChecked;
                needToPayPrice = needToPay;
            }

            @Override
            public void onConfirmClick() {
                confirmPayDialog.dismiss();
                switch (mDialogPayType) {
                    case PayConfig.WX_PAY://微信支付
                        if (WXPayUtils.checkIsSupportWXPay(mActivity))
                            invokeWXPay(mAddedOrderInfo, total, balance);

                        //                        boolean isPaySupported = wxApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                        //                        boolean isWXInstalled = wxApi.isWXAppInstalled();
                        //                        if (isPaySupported) {//微信客户端版本过低
                        //                            XToastUtils.showShortToast(getString(R.string.wx_pay_not_support));
                        //                            return;
                        //                        } else if (isWXInstalled) {//没有安装微信客户端
                        //                            XToastUtils.showShortToast(getString(R.string.wx_pay_not_installed));
                        //                            return;
                        //                        }
                        break;
                    case PayConfig.ALI_PAY://支付宝
                        invokeAliPay(mAddedOrderInfo, total, balance);
                        //                        confirmPayDialog.dismiss();
                        //                        AlertDialog alertDialog = Utils.showCornerSuccessDialog(mActivity);
                        //                        ImageView iv = (ImageView) alertDialog.findViewById(R.id.iv_title);
                        //                        iv.setImageResource(R.drawable.icon_success);

                        break;
                    //                                    case PayConfig.YUE_PAY://余额
                    //                                        confirmPayDialog.dismiss();
                    //                                        Random random = new Random();
                    //                                        int re = random.nextInt() * 10;
                    //                                        if (re < 5) {
                    //                                            CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.go_recharge), getString(R.string.yue_not_enough));
                    //                                            dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
                    //                                                @Override
                    //                                                public void left() {
                    //                                                }
                    //
                    //                                                @Override
                    //                                                public void right() {
                    //                                                }
                    //
                    //                                                @Override
                    //                                                public void middle() {
                    //                                                    dialog.dismiss();
                    //                                                }
                    //                                            });
                    //                                            dialog.show(getFragmentManager(), "yue_not_enough");
                    //                                        } else {
                    //                                            start(PayByBalanceFragment.getInstance());
                    //                                        }
                    //                                        break;
                    //                                    default:
                    //                                        XToastUtils.showShortToast(getString(R.string.please_select_pay_type));
                    //                                        break;
                }
            }

            @Override
            public void onPayTypeClick() {
                confirmPayDialog.dismiss();
                showSelectPayTypeDialog();
            }
        });
        confirmPayDialog.show(getFragmentManager(), "ConfirmPayDialog");
    }

    /**
     * 弹出选择支付方式对话框
     */
    private void showSelectPayTypeDialog() {
        payTypeSelectDialog = new PayTypeSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.PAY_TYPE, mDialogPayType);
        payTypeSelectDialog.setArguments(bundle);
        payTypeSelectDialog.setPayTypeSelectListener(type -> {
            mDialogPayType = type;
            //            mSelectPayMethodView.setPayMethod(type);
            showPayDetailDialog(mDialogPayType, mAddedOrderInfo.getPaymentPrice(), mMyBalance.getAvailableBalance(), needToPayPrice, checkBoxState);
        });
        payTypeSelectDialog.show(getFragmentManager(), "PayTypeSelectDialog");
    }


    /**
     * 充值提示框
     */
    private void showGoToChargeDialog() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.go_recharge), getString(R.string.yue_not_enough));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                //                mActivity.onBackPressedSupport();
            }

            @Override
            public void right() {
                //                dialog.dismiss();
            }

            @Override
            public void middle() {
                Utils.startActivity(mActivity, BalanceActivity.class);
            }
        });
        dialog.show(getFragmentManager(), "confirm_leave");
    }

    //    /**
    //     * 微信支付
    //     */
    //    private void payByWX(WXPay wxPay) {
    //        PayReq req = new PayReq();
    //        //        req.appId = wxPay.getAppId();
    //        req.appId = wxPay.getAppId();
    //        req.partnerId = wxPay.getPartnerId();
    //        req.prepayId = wxPay.getPrePayId();
    //        req.nonceStr = wxPay.getNonceStr();
    //        req.timeStamp = wxPay.getTimestamp();
    //        req.packageValue = "Sign=WXPay";
    //        req.sign = wxPay.getSign();//签名后台返回，签名看在本地还是服务器
    //        //        req.extData = "app data";
    //        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
    //        wxApi.sendReq(req);//支付结果在.wxapi.WXPayEntryActivity
    //    }

    /**
     * 支付宝支付
     */
    private void payByALi(String payInfo) {
        //        String payParam = payInfo;//后台返回,签名看在本地还是服务器
        AliPayUtil aliPayUtil = AliPayUtil.createInstance(mActivity, payInfo);
        aliPayUtil.setPayCallBack(new IPayCallBack() {
            @Override
            public void paySuccess() {//支付成功

                XTipsDialog.showSuccess(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_success), () -> {
                    start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ALI_PAY_SUCCESS));
                    Utils.putLastPayType(PayConfig.ALI_PAY);
                });


                //                XTipsDialog.showSuccess(mActivity, getString(R.string.pay_success), () -> start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId())));
                //                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ALI_PAY_SUCCESS));
                //                Utils.putLastPayType(PayConfig.ALI_PAY);
            }

            @Override
            public void payFailed() {//支付失败
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_failed));
//                XToastUtils.showShortToast("支付失败");
            }

            @Override
            public void payOnWaitForConfirm() {//结果等待确认
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_wait_to_confirm));
//                XToastUtils.showShortToast(LeYaoGoApplication.getContext().getString(R.string.pay_wait_to_confirm));
            }

            @Override
            public void userCanceled() {
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_cancel));
//                XToastUtils.showShortToast("支付取消");
            }
        });
        aliPayUtil.startToPay();
    }


    //    /**
    //     * 检测是否支持微信支付
    //     */
    //    private boolean checkIsSupportWXPay() {
    //        boolean isPaySupported = wxApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
    //        boolean isWXInstalled = wxApi.isWXAppInstalled();
    //        if (!isPaySupported) {//微信客户端版本过低
    //            XTipsDialog.showFail(mActivity, getString(R.string.wx_pay_not_support));
    //            return false;
    //        } else if (!isWXInstalled) {//没有安装微信客户端
    //            XTipsDialog.showFail(mActivity, getString(R.string.wx_pay_not_installed));
    //            return false;
    //        }
    //        return true;
    //    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_PAY_SUCCESS:
                Utils.putLastPayType(PayConfig.WX_PAY);
                start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                break;
        }
    }

}

